package util;

import java.sql.*;

//连接数据库类
public class BaseDao {
    private static final String driver="com.mysql.cj.jdbc.Driver";
    private static final String url="jdbc:mysql://localhost:3306/warehouse?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT";
    private static final String user="root";
    private static final String password="root";

    public static Connection getConnection() throws ClassNotFoundException, SQLException{
        //加载数据库驱动
        Class.forName(driver);
        return DriverManager.getConnection(url,user,password);
    }


    //关闭连接
    public static void close(Connection con, PreparedStatement ps, ResultSet rs){
        if(rs!=null){
            try{
                rs.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        if(ps!=null){
            try{
                ps.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        if(con!=null){
            try{
                con.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
    }

    public static boolean addUpdateDelete(String sql,Object[] arr) {
        Connection con;
        PreparedStatement ps;

        try {
            con = BaseDao.getConnection();//获取连接
            ps = con.prepareStatement(sql);//预处理
            if (arr.length != 0) {
                for (int i = 0; i < arr.length; i++) {
                    ps.setObject(i + 1, arr[i]);
                }
            }
            int count = ps.executeUpdate();//执行数据的更新
            return count > 0;
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {
        try{
            System.out.println("---测试数据库链接成功---");
            System.out.println(BaseDao.getConnection());
        }catch (ClassNotFoundException | SQLException e){
            e.printStackTrace();
        }
    }
}
